package androidvn.xenforo.fourums;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import androidvn.xenforo.fourums.R;
import androidvn.xenforo.fourums.adapter.CustomPostListAdapter;
import androidvn.xenforo.fourums.model.Post;
import androidvn.xenforo.fourums.widget.JsonParser;
import androidvn.xenforo.fourums.widget.PullAndLoadListView;
import androidvn.xenforo.fourums.widget.PullAndLoadListView.OnLoadMoreListener;
import androidvn.xenforo.fourums.widget.PullToRefreshListView.OnRefreshListener;

public class PostFragment extends ListFragment {
	private int loadMorePost = 10, index = 0;
	private ProgressDialog pDialog;
	JsonParser jsonParser = new JsonParser();
	Post post = new Post();
	ArrayList<Post> postList;
	ArrayList<Post> postListLoad;
	String threadId;

	// JSON url
	private static final String URL = "http://android.vn/api.php?action=getPosts";
	// ALL JSON node names
	private static final String TAG_POST_ID = "post_id";
	private static final String TAG_THREAD_ID = "thread_id";
	private static final String TAG_USER_ID = "user_id";
	private static final String TAG_USERNAME = "username";
	private static final String TAG_POST_DATE = "post_date";
	private static final String TAG_MESSAGE = "message";
	private static final String TAG_POSITION = "position";
	// private static final String TAG_LIKES = "likes";
	private static final String TAG_LIKE_USERS = "like_users";

	// private static final String TAG_BOX = "nameBox";

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		postList = new ArrayList<Post>();
		postListLoad = new ArrayList<Post>();
		new LoadData().execute();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.post_list_layout, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.d("On Post Params >>>", "ThreadID: " + threadId + " / Status: "
				+ Global.loginStatus + " - Username: " + Global.userName
				+ " - Hash: " + Global.userHash);

		// refresh list view
		// ((PullAndLoadListView) getListView())
		// .setOnRefreshListener(new OnRefreshListener() {
		// @Override
		// public void onRefresh() {
		// new PullRefreshList().execute();
		// }
		// });

		((PullAndLoadListView) getListView())
				.setOnLoadMoreListener(new OnLoadMoreListener() {

					@Override
					public void onLoadMore() {
						loadMorePost += 10;
						index = postList.size();
						new LoadMoreData().execute();

					}
				});
		// ((PullAndLoadListView) getListView()).onLoadMoreComplete();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		new LoadData().cancel(true);
		new LoadMoreData().cancel(true);
		// new PullRefreshList().cancel(true);
		super.onPause();

	}

	class LoadMoreData extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... agrs) {

			if (isCancelled()) {
				return null;
			}
			try {
				java.lang.Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			// parameter
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(TAG_THREAD_ID, threadId));
			params.add(new BasicNameValuePair("limit", String
					.valueOf(loadMorePost)));
			postListLoad = new ArrayList<Post>();

			JSONObject jsonRespond = jsonParser.makeHttpRequest(URL, "GET",
					params);
			// Log.d("JSON RESPOND >>>", jsonRespond.toString());
			if (jsonRespond != null) {
				try {
					JSONObject jsonThreads = jsonRespond.getJSONObject("posts");

					Iterator<?> keys = jsonThreads.keys();
					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject jsonThread = jsonThreads.getJSONObject(key);

						post = new Post();
						post.setPostId(jsonThread.getString(TAG_POST_ID));
						post.setThreadId(jsonThread.getString(TAG_THREAD_ID));
						post.setUserId(jsonThread.getString(TAG_USER_ID));
						post.setUserName(jsonThread.getString(TAG_USERNAME));
						//
						post.setPostDate(DateFormat.getDateInstance().format(
								new Date(Long.valueOf(jsonThread
										.getString(TAG_POST_DATE) + "000"))));
						//
						post.setMessage(jsonThread.getString(TAG_MESSAGE));

						post.setPosition(jsonThread.getString(TAG_POSITION));
						post.setLikeUsers(jsonThread.getString(TAG_LIKE_USERS));

						postListLoad.add(post);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			if (postList.size() < postListLoad.size()) {
				for (int i = index; i < postListLoad.size(); i++) {
					Post map2 = postListLoad.get(i);
					postList.add(map2);
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Collections.sort(postList, new Comparator<Post>() {

				@Override
				public int compare(Post lhs, Post rhs) {
					return lhs.getPosition().compareTo(rhs.getPosition());
				}
			});
			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onLoadMoreComplete();

		}

		@Override
		protected void onCancelled() {

			super.onCancelled();
		}
	}

	// refresh list view
	// class PullRefreshList extends AsyncTask<String, String, String> {
	//
	// @Override
	// protected String doInBackground(String... arg0) {
	// if (isCancelled()) {
	// return null;
	// }
	// try {
	// java.lang.Thread.sleep(3000);
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// postList.clear();
	//
	// // add new list thread
	// List<NameValuePair> params = new ArrayList<NameValuePair>();
	// params.add(new BasicNameValuePair(TAG_THREAD_ID, threadId));
	// JSONObject jsonRespond = jsonParser.makeHttpRequest(URL, "GET",
	// params);
	// if (jsonRespond != null) {
	// try {
	// JSONObject jsonThreads = jsonRespond.getJSONObject("posts");
	//
	// Iterator<?> keys = jsonThreads.keys();
	// while (keys.hasNext()) {
	// String key = (String) keys.next();
	// JSONObject jsonThread = jsonThreads.getJSONObject(key);
	//
	// post = new Post();
	// post.setPostId(jsonThread.getString(TAG_POST_ID));
	// post.setThreadId(jsonThread.getString(TAG_THREAD_ID));
	// post.setUserId(jsonThread.getString(TAG_USER_ID));
	// post.setUserName(jsonThread.getString(TAG_USERNAME));
	// //
	// String dateString = jsonThread.getString(TAG_POST_DATE);
	// Date date = new Date(Long.valueOf(dateString + "000"));
	// post.setPostDate(DateFormat.getDateInstance().format(
	// date));
	// //
	// post.setMessage(jsonThread.getString(TAG_MESSAGE));
	// post.setPosition(jsonThread.getString(TAG_POSITION));
	// post.setLikeUsers(jsonThread.getString(TAG_LIKE_USERS));
	//
	// postList.add(post);
	// }
	//
	// } catch (JSONException e) {
	// e.printStackTrace();
	// }
	// }
	// loadMorePost = 10;
	// index = 10;
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(String result) {
	// super.onPostExecute(result);
	// Collections.sort(postList, new Comparator<Post>() {
	//
	// @Override
	// public int compare(Post lhs, Post rhs) {
	// return lhs.getPosition().compareTo(rhs.getPosition());
	// }
	// });
	// ((BaseAdapter) getListAdapter()).notifyDataSetChanged();
	// ((PullAndLoadListView) getListView()).onRefreshComplete();
	// }
	//
	// @Override
	// protected void onCancelled() {
	//
	// super.onCancelled();
	// }
	//
	// }

	class LoadData extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Loading ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... arg0) {

			// building parameters

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(TAG_THREAD_ID, threadId));
			JSONObject jsonRespond = jsonParser.makeHttpRequest(URL, "GET",
					params);
			// Log.d("json respond", jsonRespond.toString());
			if (jsonRespond != null) {
				try {
					JSONObject jsonThreads = jsonRespond.getJSONObject("posts");

					Iterator<?> keys = jsonThreads.keys();
					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject jsonThread = jsonThreads.getJSONObject(key);
						
						post = new Post();
						post.setPostId(jsonThread.getString(TAG_POST_ID));
						post.setThreadId(jsonThread.getString(TAG_THREAD_ID));
						post.setUserId(jsonThread.getString(TAG_USER_ID));
						post.setUserName(jsonThread.getString(TAG_USERNAME));
						//
						post.setPostDate(DateFormat.getDateInstance().format(
								new Date(Long.valueOf(jsonThread
										.getString(TAG_POST_DATE) + "000"))));
						//
						post.setMessage(jsonThread.getString(TAG_MESSAGE));
						post.setPosition(jsonThread.getString(TAG_POSITION));
						post.setLikeUsers(jsonThread.getString(TAG_LIKE_USERS));

						postList.add(post);

					}
					Log.d("json", jsonThreads.toString());

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			pDialog.dismiss();
			Collections.sort(postList, new Comparator<Post>() {

				@Override
				public int compare(Post lhs, Post rhs) {
					return lhs.getPosition().compareTo(rhs.getPosition());
				}
			});
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					CustomPostListAdapter adapter = new CustomPostListAdapter(
							getActivity(), postList);
					setListAdapter(adapter);
				}
			});
		}
	}

	public void getThreadId(String threadId) {
		this.threadId = threadId;
	}
}
